﻿Public Class BillManager
    Inherits CoreClass

    ' Gan gia tri cho bien MenuID de kiem tra quyen cua ng dung, gia tri nay lay trog DB va dc fix
    Dim chkMenu As Integer = getIDMenu(11)

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            ' Set sự kiện submit cho nút chỉ định
            Page.Form.DefaultButton = btnSearch.UniqueID
            chkPms((CInt(Session("GroupId").ToString())), chkMenu)
            formatCbx()
            If Not Page.IsPostBack Then
                If chkView = 1 Then
                    bindStatusBill()
                    formatCbx()
                    BindGrid()
                Else
                    objAlert.ErrorBox(Page, "Bạn không có quyền truy xuất trang này, liên hệ với Admin để biết thêm chi tiết.")
                End If
            End If
        Catch ex As Exception
            Response.Redirect("/Inside/xLogin.aspx?redirect=" & Request.Url.PathAndQuery.Replace("?", "|"))
        End Try
    End Sub

#Region "Các hàm tự viết"

    ' Lấy dự liệu đưa vào Grid View
    Public Sub BindGrid()
        Try
            Dim sqlTotal = ""
            Dim sqlExp As String = ""

            sql = "select * from Out_Bill where 1=1 "
            sqlTotal = "select ISNULL(SUM(BillTotal),0) as Total from Out_Bill where 1 = 1 "
            If Not txtIdBill.Text = "" Then
                sqlExp &= " and BillID = " & objFunction.ValueCheck(txtIdBill.Text) & " "
            End If
            If Not txtName.Text = "" Then
                sqlExp &= " and BillName like N'%" & txtName.Text & "%'"
            End If

            If Not txtEmail.Text = "" Then
                sqlExp &= " and BillEmail like '%" & txtEmail.Text & "%'"
            End If

            If Not txtAddress.Text = "" Then
                sqlExp &= " and BillAddress like N'%" & txtAddress.Text & "%'"
            End If

            If Not txtPhone.Text = "" Then
                sqlExp &= " and BillPhone like '%" & txtPhone.Text & "%'"
            End If

            If Not (cbxStatus.SelectedValue = "-1" Or cbxStatus.SelectedValue = "") Then
                sqlExp &= " and BillStatus = " & objFunction.ValueCheck(cbxStatus.SelectedValue)
            End If
            If txtStartDate.Text <> "" Then
                Dim endD As Date
                If txtEndDate.Text <> "" Then
                    endD = Date.Parse(objFunction.formatDateVNtoGlobal(txtEndDate.Text))
                Else
                    endD = Date.Parse(objFunction.formatDateVNtoGlobal(txtStartDate.Text))
                End If
                endD = endD.AddDays(1)
                sqlExp &= " and BillDate >= '" & objFunction.convertDateVNtoOther(txtStartDate.Text, "ymd") & " ' and BillDate < '" & endD.Year & "-" & endD.Month & "-" & endD.Day & "'"
            End If

            sql = sql & sqlExp & " order by BillID Desc"
            dsSource.ConnectionString = ConnectionString
            dsSource.SelectCommand = sql
            grid2.DataBind()

            sqlTotal = sqlTotal & sqlExp
            Dim dts As DataSet = objDataRead.ExeDataset(sqlTotal)
            bindTotal(dts.Tables(0))

            If grid2.Rows.Count = 0 Then
                objAlert.AlertBox(Page, "Không tìm thấy dữ liệu phù hợp với yêu cầu của bạn, hãy thử lại.")
            End If
        Catch ex As Exception
            If objConfig.Developer.Equals("1") Then
                objAlert.ErrorBox(Page, "File: " & (New System.Diagnostics.StackTrace).GetFrame(0).GetMethod.DeclaringType.Name & _
                                  " --- Function: " & (New System.Diagnostics.StackTrace).GetFrame(0).GetMethod.Name & _
                                  " --- Mess: " & ex.Message.Replace("'", """"))
            Else
                objAlert.ErrorBox(Page, "Lỗi kỹ thuật, hãy thông báo lại với Admin, xin cảm ơn.")
            End If
        End Try
    End Sub

    ' Format số tổng tiền đơn hàng lấy từ dât table truyền vào
    Private Sub bindTotal(ByVal tbl As DataTable)
        Dim row As DataRow
        row = tbl.Rows(0)
        lblTotal.Text = objFunction.formatVNCurrency(row("Total")) & " đ"
    End Sub

    ' Tạo trạng thái cho combobox Status
    Private Sub bindStatusBill()
        Try
            cbxStatus.Items.Insert(0, New ListItem("-- Tất cả --", "-1"))
            cbxStatus.Items.Insert(1, New ListItem("-- Chờ duyệt --", "0"))
            cbxStatus.Items.Insert(2, New ListItem("-- Đã duyệt --", "1"))
            cbxStatus.Items.Insert(3, New ListItem("-- Đã thanh toán --", "2"))
        Catch ex As Exception
            If objConfig.Developer.Equals("1") Then
                objAlert.ErrorBox(Page, "File: " & (New System.Diagnostics.StackTrace).GetFrame(0).GetMethod.DeclaringType.Name & _
                                  " --- Function: " & (New System.Diagnostics.StackTrace).GetFrame(0).GetMethod.Name & _
                                  " --- Mess: " & ex.Message.Replace("'", """"))
            Else
                objAlert.ErrorBox(Page, "Lỗi kỹ thuật, hãy thông báo lại với Admin, xin cảm ơn.")
            End If
        End Try

    End Sub

    ' Format màu sắc cho các Drop Down List
    Private Sub formatCbx()
        Try
            ' format cho combo box STATUS
            cbxStatus.Items(1).Attributes.Add("style", "color:red;background-color:White;")
            cbxStatus.Items(2).Attributes.Add("style", "color:orange;background-color:White;")
            cbxStatus.Items(3).Attributes.Add("style", "color:green;background-color:White;")
        Catch ex As Exception

        End Try
    End Sub

    ' Format status trên grid view
    Public Function formatStatus(ByVal srtStt As String) As String
        Dim stt As Integer = 0
        Try
            stt = Integer.Parse(srtStt)
            If stt = 1 Then
                Return "<span style=""font-weight:bold;color: orange;""><b>Đã duyệt</b></span>"
            ElseIf stt = 2 Then
                Return "<span style=""font-weight:bold;color: green;""><b>Đã thanh toán</b></span>"
            Else
                Return "<span style=""font-weight:bold;color: red;""><b>Chờ duyệt</b></span>"
            End If
        Catch ex As Exception
            If objConfig.Developer.Equals("1") Then
                objAlert.ErrorBox(Page, "File: " & (New System.Diagnostics.StackTrace).GetFrame(0).GetMethod.DeclaringType.Name & _
                                  " --- Function: " & (New System.Diagnostics.StackTrace).GetFrame(0).GetMethod.Name & _
                                  " --- Mess: " & ex.Message.Replace("'", """"))
            Else
                objAlert.ErrorBox(Page, "Lỗi kỹ thuật, hãy thông báo lại với Admin, xin cảm ơn.")
            End If
        End Try

    End Function

    ' Format định dạng tiền VND trên Grid
    Public Function formatCurrency(ByVal currency As String) As String
        Dim temp As Double = Double.Parse(currency)
        Return String.Format("{0:#,##0}", temp) & " đ"
    End Function

    ' Ham hien thi ngay thang tren grid view
    Public Function formatTime(ByVal str As String) As String
        Dim tempDate As New Date
        tempDate = CDate(str)
        Dim strDateReturn = tempDate.Day & "-" & tempDate.Month & "-" & tempDate.Year
        Dim strTimeReturn = tempDate.Hour & ":" & tempDate.Minute & "  " & tempDate.Second
        Return strDateReturn & "<span style=""font-style:italic;font-size:11px;color: #808080"">(" & strTimeReturn & ")</span>"
    End Function

#End Region

#Region "Các sự kiện của Component"

#Region "Grid"

    ' Bind lại dữ liệu khi chuyển trang
    Private Sub grid2_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grid2.PageIndexChanging
        BindGrid()
    End Sub

    ' Format row trên grid
    Private Sub grid2_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grid2.RowCreated
        Try
            'Add CSS class on normal row.
            If e.Row.RowType = DataControlRowType.DataRow And e.Row.RowState = DataControlRowState.Normal Then
                e.Row.CssClass = "normal hand"
            End If

            'Add CSS class on alternate row.
            If e.Row.RowType = DataControlRowType.DataRow And e.Row.RowState = DataControlRowState.Alternate Then
                e.Row.CssClass = "alt hand"
            End If

            ' Thêm sự kiên click row để chỉnh sửa thông tin User
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim datakey As String = grid2.DataKeys(e.Row.RowIndex).Value.ToString()     'get the datakey
                e.Row.Attributes.Add("onclick", "window.location='BillDetail.aspx?id=" & datakey & "'")
            End If
        Catch ex As Exception

        End Try


    End Sub

    ' Bind lại dữ liệu khi sắp xếp
    Private Sub grid2_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grid2.Sorting
        BindGrid()
    End Sub

#End Region



#End Region

    ' Bind lại dữ liệu khi search 
    Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        BindGrid()
    End Sub

    



End Class